package com.cloudweb.dingding;
import ch.qos.logback.core.net.SyslogOutputStream;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudwebsoft.framework.util.LogUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.redmoon.dingding.service.auth.AuthService;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


/**
 * 钉钉工具类
 */
@Slf4j
public class DingDingUtil {

    private final static String SYSTEM_ERROR ="SYSTEM_ERROR";

    // 应用的appKey 自己补充
    public final static String appKey = "dingmqsgf67bti90ozrv";
    // 应用的appSecret
    private final static String appSecret="5CPyVMna6AcrsGgMaKxXPKABKzsMesIlqn5bQVHGf5R7dYaShpP1bkZ6Y2WUwqXQ";

    private final static Long AGENTID = 0L;

    private static String accessTokenUrl = "https://oapi.dingtalk.com/gettoken";//通用
    private static String userUrl = "https://oapi.dingtalk.com/topapi/v2/user/get";
    private static String mobileUrl = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";//通过手机号查询用户
    private static String checkInUrl = "https://oapi.dingtalk.com/topapi/checkin/record/get";
    private static String getAttendanceList = "https://oapi.dingtalk.com/attendance/list";//获取打卡结果
    private static String getAttendanceListRecord = "https://oapi.dingtalk.com/attendance/listRecord";//获取打卡详情


    //获取token(系统另有接口 AuthService.getAccessToken() )
//    public static String getToken (){
//        Object object = LocalCacheClient.get("access_token");
//        if(object != null){
//            return object.toString();
//        }
//        DefaultDingTalkClient client = new
//                DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
//        OapiGettokenRequest req = new OapiGettokenRequest();
//        req.setAppkey(DingDingUtil.appKey);
//        req.setAppsecret(DingDingUtil.appSecret);
//        req.setHttpMethod("GET");
//        try {
//            OapiGettokenResponse response = client.execute(req);
//            LocalCacheClient.set("access_token", response.getAccessToken(),7200*1000);
//            if(!response.isSuccess()) {
//                log.error("调用钉钉接口失败："+response.getMessage());
//            }
//            return response.getAccessToken();
//        } catch (ApiException e) {
//            log.error(DingDingUtil.SYSTEM_ERROR, e);
//        }
//        return null;
//    }

    //获取部门列表
    public static List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDepartment(){
        String access_token = AuthService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        //获取根部门下所有部门列表  根部门的部门id为1
//        request.setDeptId(1L);
        req.setHttpMethod("GET");
        try {
            OapiV2DepartmentListsubResponse response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess() ? response.getResult():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取员工ID 2试用 3在职 5离职 -1无状态
    public static List<String> getUserIdByStatus(String statusList){
        String access_token = AuthService.getAccessToken();
        try {
            Long limit = 0L,size = 0L;
            int paging = 0;//分页
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
            OapiSmartworkHrmEmployeeQueryonjobRequest req = new OapiSmartworkHrmEmployeeQueryonjobRequest();
            OapiSmartworkHrmEmployeeQueryonjobResponse response;
            JSONArray jsonArray = new JSONArray();
            jsonArray = null;
            List<String> userList = null;

            do{
                limit = Long.valueOf(paging * 50);
                size = limit + 50L;
                req.setStatusList(statusList);//2,3,5,-1
                req.setOffset(limit);
                req.setSize(size);

                response = client.execute(req, access_token);
                if(response != null || response.getErrcode() == 0 || response.getErrcode() != null){
//                    userList = response.getResult().getDataList();
                    if(response.getResult().getDataList().size() >0 ){
                        System.out.println(response.getResult().getDataList());
                        List list = response.getResult().getDataList();
                        jsonArray = new JSONArray(list);

                    }else if(response == null){
                        LogUtil.getLog(DingDingUtil.class).info("获取员工ID getUserIdByStatus 请求失败");
                    }else{
                        if(paging == 0){
                            LogUtil.getLog(DingDingUtil.class).info("员工列表为空");
                        }else{
                            LogUtil.getLog(DingDingUtil.class).info("第"+(paging+1) +"页为空");
                        }
//                        jsonArray.add(null);
                    }
                    System.out.println(response.getResult().getNextCursor());
                    System.out.println(response.getBody().contains("next_cursor"));
                    paging++;
                }else{
                    break;
                }

            }while (response != null && response.getBody().contains("next_cursor"));

//            String result = response.getBody();
            LogUtil.getLog(DingDingUtil.class).info("获取员工ID:"+jsonArray);
            assert jsonArray != null;
            userList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                userList.add(jsonArray.getString(i));
            }
            return userList;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取部门下的所有用户列表
    public static List<String> getDepartmentUserId(Long departmentId){
        String access_token = AuthService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
        OapiUserListidRequest req = new OapiUserListidRequest();
        req.setDeptId(departmentId);

        try {
            OapiUserListidResponse response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getResult().getUseridList():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取部门下的所有用户列表
    public static OapiV2UserListResponse.PageResult getDepartmentUser(Long departmentId, long cursor, long size){
        String access_token = AuthService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
        OapiV2UserListRequest req = new OapiV2UserListRequest();
        req.setDeptId(departmentId);
        req.setCursor(cursor);
        req.setSize(size);
        req.setOrderField("modify_desc");
        req.setHttpMethod("GET");

        try {
            OapiV2UserListResponse response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getResult():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取钉钉考勤记录-打卡结果
    public static OapiAttendanceListResponse getAttendanceList(String startWorkDate, String endWorkDate, List<String> userIdList, long offset, long limit,boolean isI18n){
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/list");
            OapiAttendanceListRequest req = new OapiAttendanceListRequest();
            req.setWorkDateFrom(startWorkDate);
            req.setWorkDateTo(endWorkDate);
            req.setUserIdList(userIdList);
            req.setOffset(offset);
            req.setLimit(limit);
            req.setIsI18n(isI18n);
            OapiAttendanceListResponse rsp = client.execute(req, access_token);
            String result = rsp.getBody();
            LogUtil.getLog(DingDingUtil.class).info("打卡结果:"+result);
            return rsp;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }


        return null;
    }

    //获取钉钉考勤记录-打卡结果2
    public static List<OapiAttendanceListResponse.Recordresult> getAttendanceList2(String startWorkDate, String endWorkDate, List<String> userIdList, long offset, long limit,boolean isI18n) {
        String access_token = AuthService.getAccessToken();
        // 通过调用接口获取考勤打卡结果
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient(getAttendanceList);
        OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        // 查询考勤打卡记录的起始工作日
        req.setWorkDateFrom(startWorkDate);
        // 查询考勤打卡记录的结束工作日
        req.setWorkDateTo(endWorkDate);
        // 员工在企业内的userid列表，最多不能超过50个
        req.setUserIdList(userIdList);
        // 表示获取考勤数据的起始点
        req.setOffset(offset);
        // 表示获取考勤数据的条数，最大不能超过50条。
        req.setLimit(limit);
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(req,access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getRecordresult():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;

    }



    //获取钉钉考勤记录-打卡详情
    public static List<OapiAttendanceListResponse.Recordresult> getAttendanceListRecord(String checkDateFrom, String checkDateTo, List<String> userIdList, boolean isI18n) {
        String access_token = AuthService.getAccessToken();
        DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/attendance/listRecord");
        OapiAttendanceListRequest req = new OapiAttendanceListRequest();
        req.setUserIdList(userIdList);
        req.setWorkDateFrom(checkDateFrom);
        req.setWorkDateTo(checkDateTo);
        req.setIsI18n(isI18n);//是否国际化
        OapiAttendanceListResponse response = null;
        try {
            response = clientDingTalkClient.execute(req,access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getRecordresult():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取用户当天的考勤数据，包括打卡流水记录、打卡结果和审批列表等
    public static String getAttendance(String userId ,String work_date){
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getupdatedata");
            OapiAttendanceGetupdatedataRequest req = new OapiAttendanceGetupdatedataRequest();
            req.setUserid(userId);
            req.setWorkDate(StringUtils.parseDateTime(work_date));
            OapiAttendanceGetupdatedataResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
            String result = rsp.getBody();
            return result;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }


    //通过手机号查询用户信息：{"errcode":0,"errmsg":"ok","result":{"userid":"114658655020896248"},"request_id":"16m94nctmwc3n"}
    public static String getUserIdByMobile(String phone) {
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, access_token);
            String result = rsp.getBody();
            LogUtil.getLog(DingDingUtil.class).info("通过手机号查询用户信息:"+result);
            return result;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    /**
     * 获取用户签到记录
     * @param startTime
     * @param endTime
     * @param userIdStr
     * @param maxSize
     * @return
     * @throws Exception
     */
    //{"errcode":0,"result":{"page_list":[]},"errmsg":"ok","request_id":"16ly1sj09ncao"}
    public static JSONObject getCheckinList(Long startTime, Long endTime, String userIdStr,long maxSize) throws Exception {
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/checkin/record/get");
            OapiCheckinRecordGetRequest req = new OapiCheckinRecordGetRequest();
            req.setUseridList(userIdStr);
            req.setStartTime(startTime);
            req.setEndTime(endTime);
            req.setCursor(0L);//0~条
            req.setSize(maxSize);
            OapiCheckinRecordGetResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
            String result = rsp.getBody();
            JSONObject resutJSON = JSONObject.parseObject(result);
            Integer errcode = resutJSON.getInteger("errcode");
            LogUtil.getLog(DingDingUtil.class).info("errcode:"+errcode);
            JSONObject jsonArray = null;
            if (errcode == 0) {
                jsonArray = (JSONObject) resutJSON.get("result");
            }
            return jsonArray;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取考勤组列表详情
    public static String getsimplegroups(){
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/attendance/getsimplegroups");
            OapiAttendanceGetsimplegroupsRequest req = new OapiAttendanceGetsimplegroupsRequest();
            OapiAttendanceGetsimplegroupsResponse rsp = client.execute(req, access_token);
            String result = rsp.getBody();
            LogUtil.getLog(DingDingUtil.class).info("考勤组详情:"+result);
            return result;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }


    //给用户推送消息（文字消息）
    public static Object pushUser(String userIds,String content){
        String access_token = AuthService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

        OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
        req.setUseridList(userIds);
        req.setAgentId(AGENTID);
        req.setToAllUser(false);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
        msg.getText().setContent(content);
        req.setMsg(msg);

        try {
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取审批实例ID列表
    public static OapiProcessinstanceListidsResponse.PageResult getProcessinstanceListid(String processCode, Long startTime, Long endTime, long cursor, long size) {
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/listids");
            OapiProcessinstanceListidsRequest req = new OapiProcessinstanceListidsRequest();
            req.setProcessCode(processCode);
            req.setStartTime(startTime);
            if(endTime != null) {
                req.setEndTime(endTime);
            }
            req.setSize(size);
            req.setCursor(cursor);
            OapiProcessinstanceListidsResponse response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getResult():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }

    //获取审批实例详情
    public static OapiProcessinstanceGetResponse.ProcessInstanceTopVo getProcessinstanceInfo(String processInstanceId) {
        String access_token = AuthService.getAccessToken();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();
            req.setProcessInstanceId(processInstanceId);
            OapiProcessinstanceGetResponse response = client.execute(req, access_token);
            if(!response.isSuccess()) {
                log.error("调用钉钉接口失败："+response.getMessage());
            }
            return response.isSuccess()?response.getProcessInstance():null;
        } catch (ApiException e) {
            log.error(DingDingUtil.SYSTEM_ERROR, e);
        }
        return null;
    }




}
